package com.yxsk.relay.job.endpoint.combine.auto.config.components;

import com.yxsk.relay.job.component.common.protocol.caller.RemoteCaller;
import com.yxsk.relay.job.component.common.thread.lifecycle.ThreadLifecycle;
import com.yxsk.relay.job.component.common.thread.observe.ObservableThread;
import com.yxsk.relay.job.component.endpoint.registry.SigningTask;
import com.yxsk.relay.job.endpoint.combine.auto.config.properties.RelayJobAdminConfigProperties;
import com.yxsk.relay.job.endpoint.combine.auto.config.properties.RelayJobSlaveConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description
 * @Author 11376
 * @CreateTime 2019/9/14 22:49
 */
@Configuration
@AutoConfigureOrder(5)
public class AdminRegistryConfig {

    @Bean(destroyMethod = "shutdown")
    public SigningTask signingTask(RelayJobAdminConfigProperties adminConfigProperties, RelayJobSlaveConfigProperties slaveConfigProperties, RemoteCaller remoteCaller) {
        return new SigningTask(adminConfigProperties, slaveConfigProperties, remoteCaller);
    }

    @Bean
    public SignTaskLifecycle signTaskLifecycle() {
        return new SignTaskLifecycle();
    }

    @Bean(initMethod = "start")
    public ObservableThread signThread(SigningTask signingTask) {
        return new ObservableThread(signTaskLifecycle(), signingTask);
    }

    @Slf4j
    private static class SignTaskLifecycle implements ThreadLifecycle {

        @Override
        public void onNew() {
            if (log.isDebugEnabled()) {
                log.debug("Relay job sign task init.");
            }
        }

        @Override
        public void onStart(Thread thread) {
            if (log.isDebugEnabled()) {
                log.debug("Relay job sign task started.");
            }
        }

        @Override
        public void onRunning(Thread thread) {
            if (log.isDebugEnabled()) {
                log.debug("Relay job sign task running...");
            }
        }

        @Override
        public void onFinish(Thread thread, Object o) {
            if (log.isDebugEnabled()) {
                log.debug("Relay job sign task shutdown.");
            }
        }

        @Override
        public void onError(Thread thread, Exception e) {
            log.error("Relay job sign task error.", e);
        }
    }

}
